import React, { useEffect } from "react"
import { lazy } from "react"
import Home from "@/views/Home"
import { useSelector } from 'react-redux';
import NotFound from "@/views/NotFound"
import { Navigate, RouteObject,useNavigate, Outlet } from "react-router-dom"
import Login from "@/views/Login"
const About = lazy(() => import("@/views/About"))
const News = lazy(() => import("@/views/News"))
const News2 = lazy(() => import("@/views/News2"))

export const BeforRouterEnter = () => {
    const token = useSelector((state:any) => state.token_reducer.token);
    let navigate = useNavigate();
    useEffect(() => {
      if (!token) {
        navigate('/login', { replace: true });
      }
    }, [token, navigate]);
    return token ? <Outlet /> : null;
}

const withLoadingComponent = (compont:JSX.Element):JSX.Element => (
    <React.Suspense fallback={<div>Loading...</div>} >
    {compont}
    </React.Suspense>
)
const routes: RouteObject[] = [
    {
        path: '/',
        element: <Navigate to='/news' />
    },
    {
        path: "/",
        element: <Home/>,
        children: [
            {
                path: 'news',
                element: withLoadingComponent(<News />)
            },
            {
                path: 'user/news2',
                element: withLoadingComponent(<News2 />)
            },
            {
                path: 'user/about',
                element: withLoadingComponent(<About />)
            }
        ]
    },
    {
        path: "/Login",
        element: <Login />
    },
    {
        path: "*",
        element: <Navigate to="/404" />
    },
    {
        path: "/404",
        element: <NotFound/>
    }
]
export default routes
